#region Using

using System;
using System.IO;
using System.Data;
using BlogEngine.Core;

#endregion

namespace BlogEngine.Core.Providers
{
    /// <summary>
    /// Microsoft SQL Server Implementation of BlogProvider
    /// </summary>
    public partial class MSSQLBlogProvider : BlogProviderBase
    {

        //Extension Settings
        /// <summary>
        /// Loads the extension settings to the provider..
        /// </summary>
        /// <returns></returns>
        public override Stream LoadExtensionSettings()
        {
            SQLManagedConnection myConn = SQLManagedConnection.GetConnection(_DatabaseName);

            try
            {
                myConn.GetTextCommand("SELECT Settings FROM be_ExtensionSettings");
                object o = myConn.ExecuteScalar();

                if (o == null)
                    return null;

                return new MemoryStream((byte[])o);
            }
            finally
            {
                myConn.CloseIfNonTransactional();
            }
        }

        /// <summary>
        /// Saves the extension settings to the provider.
        /// </summary>
        /// <param name="settings">The settings.</param>
        public override void SaveExtensionSettings(Stream settings)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");

            byte[] file = new byte[settings.Length];

            settings.Seek(0, SeekOrigin.Begin);
            settings.Read(file, 0, (int)settings.Length);

            SQLManagedConnection myConn = SQLManagedConnection.GetConnection(_DatabaseName);

            try
            {
                myConn.GetTextCommand("DELETE FROM be_ExtensionSettings; " +
                                      "INSERT INTO be_ExtensionSettings (Settings) VALUES (@file)");
                myConn.AddInParameter("@file", DbType.Binary, file);
                myConn.ExecuteNonQuery();
            }
            finally
            {
                myConn.CloseIfNonTransactional();
            }
        }
    }
}
